package com.rq.rvlibrary;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 打包后的文件移动处理
 */
public class ApkFileMoveR {
    /**
     * 将不同渠道的apk移到同一个位置
     * <p>
     * <p>
     * <源文件夹>\<24长度>\\*.apk
     * 将APK移到同一个文件夹(文件名前24位建立的新文件夹)  并删除源数据及其文件夹 源文件夹删除列表如下
     * <源文件夹>\**\release
     *
     * @param args
     */

    private static final String MOVE_ROOT = "E:\\LoveApplication\\app";

    public static void main(String[] args) {
        try {
            searchAndMove(MOVE_ROOT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void searchAndMove(String sourceFolder) {
        String vNameAndTime = searchApkAndMoveInFile(sourceFolder, sourceFolder);
        searchMappingAndMoveInFile(sourceFolder, sourceFolder, vNameAndTime);
    }

    private static String verAndTimeName;

    private static String searchApkAndMoveInFile(String sourceFolder, String target) {
        File folder = new File(sourceFolder);
        if (!folder.exists() || !folder.isDirectory()) {
            System.out.println("错误：指定的路径不存在或不是文件夹");
        }

        File[] files = folder.listFiles();
        if (files == null) {
            System.out.println("无法读取文件夹内容");
        }

        Pattern apkPattern = Pattern.compile("^R.*\\.apk$", Pattern.CASE_INSENSITIVE);
        Pattern vNameAndTimePattern = Pattern.compile(".*(v[0-9._]+)[0-9]{2}_.*", Pattern.CASE_INSENSITIVE);
        Set<String> needDelete = new HashSet<>();
        for (File file : files) {
            if (file.isFile() && apkPattern.matcher(file.getName()).matches()) {
                Matcher nameAndTime = vNameAndTimePattern.matcher(file.getName());
                if (nameAndTime.find()) {
                    verAndTimeName = nameAndTime.group(1);
                }
                try {
                    String originalName = file.getName();
                    String baseName = originalName.substring(0, originalName.lastIndexOf('.'));
                    String extension = ".apk";
                    String newName = baseName + extension;
                    int counter = 1;
                    if (!new File(target + "\\" + baseName.substring(0, 24)).exists()) {
                        new File(target + "\\" + baseName.substring(0, 24)).mkdirs();
                    }
                    // 处理文件名冲突
                    while (new File(folder, newName).exists() && !newName.equals(originalName)) {
                        newName = baseName + "_copy" + (++counter) + extension;
                    }

                    // 执行复制操作
                    Path sourcePath = Paths.get(file.getAbsolutePath());
                    Path targetPath = Paths.get(target + "\\" + baseName.substring(0, 24), newName);

                    Files.copy(sourcePath, targetPath);
                    needDelete.add(sourcePath.getParent().getParent().toString());
                    System.out.println("成功复制: " + originalName + " --> " + newName);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("复制文件 " + file.getName() + " 失败: " + e.getMessage());
                }
            } else if (file.isDirectory()) {
                searchApkAndMoveInFile(file.getAbsolutePath(), target);
            }
        }
        if (!needDelete.isEmpty()) {
            for (String path : needDelete) {
                try {
                    boolean delete = delete(new File(path));
                    System.out.println(path + ".delete:" + delete);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return verAndTimeName;
    }

    private static void searchMappingAndMoveInFile(String sourceFolder, String target, String vNameAndTime) {
        File folder = new File(sourceFolder);
        if (!folder.exists() || !folder.isDirectory()) {
            System.out.println("错误：指定的路径不存在或不是文件夹");
            return;
        }

        File[] files = folder.listFiles();
        if (files == null) {
            System.out.println("无法读取文件夹内容");
            return;
        }

        Pattern mapingPattern = Pattern.compile("^mapping.txt$", Pattern.CASE_INSENSITIVE);
        for (File file : files) {
            if (file.isFile() && mapingPattern.matcher(file.getName()).matches()) {
                System.out.println("Find file name:" + file.getName());
                try {
                    String allPath = file.getAbsolutePath();
                    String parentDirName = allPath.substring(allPath.indexOf("\\mapping\\") + 9, allPath.lastIndexOf("\\"));
                    String newName = "mapping_" + parentDirName + ".txt";
//                    // 执行复制操作
                    Path targetDir = Paths.get(target + "\\mapping_" + vNameAndTime);
                    if (!Files.exists(targetDir)) {
                        Files.createDirectories(targetDir);
                    }
                    System.out.println("target:" + targetDir);
                    Path sourcePath = Paths.get(file.getAbsolutePath());
                    Path targetPath = Paths.get(targetDir.toString(), newName);

                    Files.copy(sourcePath, targetPath);
                    System.out.println("成功复制: " + sourcePath + " -> " + targetPath);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (file.isDirectory()) {
                searchMappingAndMoveInFile(file.getAbsolutePath(), target, vNameAndTime);
            }
        }
    }

    public static boolean delete(File file) throws IOException {
        if (file.isDirectory()) {
            File[] listFiles = file.listFiles();
            if (listFiles != null) {
                for (File f : listFiles) {
                    if (f.isDirectory()) {
                        delete(f);
                    }
                    if (file.getPath().length() <= MOVE_ROOT.length()) {
                        return false;
                    }
                    f.delete();
                }
            }
        }
        if (file.getPath().length() <= MOVE_ROOT.length()) {
            return false;
        }
        return file.delete();
    }
}
